package com.chisheng.caa.convertor;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.chisheng.caa.exception.IllegalCellValueException;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 修读学期列值转换器
 */
public class StudyingTermConverter implements Converter<Integer> {

    /**
     * 修改学期值正则匹配表达式
     */
    private static final Pattern SUPPORTED_VALUES = Pattern.compile("^未设定|第(\\w+)学期$");

    @Override
    public Class<?> supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Integer convertToJavaData(ReadConverterContext<?> context) {
        String value = Objects.requireNonNullElse(context.getReadCellData().getStringValue(), "");
        Matcher matcher = SUPPORTED_VALUES.matcher(value);
        if (matcher.matches()) {
            return Integer.parseInt(Objects.requireNonNullElse(matcher.group(1), "0"));
        }

        throw new IllegalCellValueException(String.format("'修读学期' 列无法解析的取值: '%s'", value));
    }

}